<template>
  <div class="car-inspection-list">
    <div class="header">
      <h3>检查记录</h3>
      <el-button v-if="isAdmin" type="primary" size="small" @click="handleAddInspection">
        <el-icon><Plus /></el-icon>添加检查记录
      </el-button>
    </div>

    <div v-loading="loading">
      <el-empty v-if="inspections.length === 0" description="暂无检查记录" />
      
      <el-timeline v-else>
        <el-timeline-item
          v-for="inspection in inspections"
          :key="inspection.inspectionId"
          :type="getInspectionType(inspection.result)"
          :color="getInspectionColor(inspection.result)"
          :timestamp="formatDate(inspection.inspectionDate)"
          placement="top"
        >
          <el-card class="inspection-card">
            <template #header>
              <div class="card-header">
                <span>
                  检查结果：
                  <el-tag :type="getInspectionTagType(inspection.result)">
                    {{ inspection.result }}
                  </el-tag>
                </span>
                <div class="operations" v-if="isAdmin">
                  <el-button link type="primary" @click="handleEditInspection(inspection)">编辑</el-button>
                  <el-button link type="danger" @click="handleDeleteInspection(inspection)">删除</el-button>
                </div>
              </div>
            </template>
            <div class="inspection-content">
              <p><strong>检查员：</strong>{{ inspection.inspector }}</p>
              
              <el-collapse v-if="inspection.exteriorCondition || inspection.interiorCondition || 
                               inspection.mechanicalCondition || inspection.electricalCondition">
                <el-collapse-item title="检查详情">
                  <div v-if="inspection.exteriorCondition">
                    <p><strong>外观状况：</strong>{{ inspection.exteriorCondition }}</p>
                  </div>
                  <div v-if="inspection.interiorCondition">
                    <p><strong>内饰状况：</strong>{{ inspection.interiorCondition }}</p>
                  </div>
                  <div v-if="inspection.mechanicalCondition">
                    <p><strong>机械状况：</strong>{{ inspection.mechanicalCondition }}</p>
                  </div>
                  <div v-if="inspection.electricalCondition">
                    <p><strong>电气状况：</strong>{{ inspection.electricalCondition }}</p>
                  </div>
                </el-collapse-item>
              </el-collapse>
              
              <div v-if="inspection.reportUrl" class="report-link">
                <el-button link type="primary" @click="viewReport(inspection)">
                  <el-icon><Document /></el-icon> 查看报告
                </el-button>
              </div>
            </div>
          </el-card>
        </el-timeline-item>
      </el-timeline>
    </div>

    <!-- 添加/编辑检查记录对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
    >
      <el-form :model="form" ref="formRef" label-width="120px" :rules="rules">
        <el-form-item label="检查员" prop="inspector">
          <el-input v-model="form.inspector" placeholder="请输入检查员姓名" />
        </el-form-item>
        <el-form-item label="检查日期" prop="inspectionDate">
          <el-date-picker
            v-model="form.inspectionDate"
            type="datetime"
            placeholder="选择检查日期时间"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="外观状况" prop="exteriorCondition">
          <el-input v-model="form.exteriorCondition" type="textarea" rows="2" placeholder="请输入外观状况" />
        </el-form-item>
        <el-form-item label="内饰状况" prop="interiorCondition">
          <el-input v-model="form.interiorCondition" type="textarea" rows="2" placeholder="请输入内饰状况" />
        </el-form-item>
        <el-form-item label="机械状况" prop="mechanicalCondition">
          <el-input v-model="form.mechanicalCondition" type="textarea" rows="2" placeholder="请输入机械状况" />
        </el-form-item>
        <el-form-item label="电气状况" prop="electricalCondition">
          <el-input v-model="form.electricalCondition" type="textarea" rows="2" placeholder="请输入电气状况" />
        </el-form-item>
        <el-form-item label="报告URL" prop="reportUrl">
          <el-input v-model="form.reportUrl" placeholder="请输入报告URL" />
        </el-form-item>
        <el-form-item label="检查结果" prop="result">
          <el-select v-model="form.result" placeholder="请选择检查结果">
            <el-option label="通过" value="通过" />
            <el-option label="需维修" value="需维修" />
            <el-option label="不通过" value="不通过" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, defineProps, defineEmits } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getInspectionsByCarId, 
  addInspection, 
  updateInspection, 
  deleteInspection 
} from '@/api/inspection'
import { Plus, Document } from '@element-plus/icons-vue'

const props = defineProps({
  carId: {
    type: [Number, String],
    required: true
  },
  isAdmin: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['refresh'])

const loading = ref(false)
const inspections = ref([])
const dialogVisible = ref(false)
const dialogTitle = ref('添加检查记录')
const isEdit = ref(false)

// 表单数据
const form = ref({
  inspectionId: undefined,
  carId: props.carId,
  inspector: '',
  inspectionDate: new Date().toISOString().slice(0, 19).replace('T', ' '),
  exteriorCondition: '',
  interiorCondition: '',
  mechanicalCondition: '',
  electricalCondition: '',
  reportUrl: '',
  result: '通过'
})

// 表单规则
const rules = {
  inspector: [
    { required: true, message: '请输入检查员姓名', trigger: 'blur' }
  ],
  inspectionDate: [
    { required: true, message: '请选择检查日期', trigger: 'change' }
  ],
  result: [
    { required: true, message: '请选择检查结果', trigger: 'change' }
  ]
}

// 获取检查记录
const fetchInspections = async () => {
  loading.value = true
  try {
    const response = await getInspectionsByCarId(props.carId)
    inspections.value = response || []
  } catch (error) {
    console.error('获取检查记录失败:', error)
    ElMessage.error('获取检查记录失败')
  } finally {
    loading.value = false
  }
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  return new Date(date).toLocaleString()
}

// 获取检查类型图标
const getInspectionType = (result) => {
  switch (result) {
    case '通过': return 'success'
    case '需维修': return 'warning'
    case '不通过': return 'danger'
    default: return 'info'
  }
}

// 获取检查颜色
const getInspectionColor = (result) => {
  switch (result) {
    case '通过': return '#67C23A'
    case '需维修': return '#E6A23C'
    case '不通过': return '#F56C6C'
    default: return '#909399'
  }
}

// 获取标签类型
const getInspectionTagType = (result) => {
  switch (result) {
    case '通过': return 'success'
    case '需维修': return 'warning'
    case '不通过': return 'danger'
    default: return 'info'
  }
}

// 添加检查记录
const handleAddInspection = () => {
  isEdit.value = false
  dialogTitle.value = '添加检查记录'
  form.value = {
    inspectionId: undefined,
    carId: props.carId,
    inspector: '',
    inspectionDate: new Date().toISOString().slice(0, 19).replace('T', ' '),
    exteriorCondition: '',
    interiorCondition: '',
    mechanicalCondition: '',
    electricalCondition: '',
    reportUrl: '',
    result: '通过'
  }
  dialogVisible.value = true
}

// 编辑检查记录
const handleEditInspection = (inspection) => {
  isEdit.value = true
  dialogTitle.value = '编辑检查记录'
  form.value = { ...inspection }
  dialogVisible.value = true
}

// 删除检查记录
const handleDeleteInspection = (inspection) => {
  ElMessageBox.confirm('确定要删除这条检查记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteInspection(inspection.inspectionId)
      ElMessage.success('删除成功')
      fetchInspections()
      emit('refresh')
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}

// 查看报告
const viewReport = (inspection) => {
  if (!inspection.reportUrl) {
    ElMessage.warning('没有报告可查看')
    return
  }
  window.open(inspection.reportUrl, '_blank')
}

// 提交表单
const handleSubmit = async () => {
  const formRef = ref(null)
  
  try {
    if (isEdit.value) {
      await updateInspection(form.value)
      ElMessage.success('更新成功')
    } else {
      await addInspection(form.value)
      ElMessage.success('添加成功')
    }
    dialogVisible.value = false
    fetchInspections()
    emit('refresh')
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败')
  }
}

onMounted(() => {
  fetchInspections()
})
</script>

<style scoped>
.car-inspection-list {
  padding: 10px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h3 {
  margin: 0;
  font-size: 18px;
}

.inspection-card {
  margin-bottom: 10px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.operations {
  display: flex;
  gap: 10px;
}

.inspection-content {
  margin-top: 10px;
}

.report-link {
  margin-top: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 